import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'

Vue.use(VueRouter)

// 解决编程式路由往同一地址跳转时会报错的情况🍗
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace

// push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  // if (onResolve || onReject) {
  //   return originalPush.call(this, location, onResolve, onReject)
  // }
  return originalPush.call(this, location).catch((err) => err)
}

// replace
VueRouter.prototype.replace = function push (location, onResolve, onReject) {
  // if (onResolve || onReject) {
  //   return originalReplace.call(this, location, onResolve, onReject)
  // }
  return originalReplace.call(this, location).catch((err) => err)
}

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/reg',
    component: () => import('@/views/register/index.vue')
  },
  {
    path: '/main',
    component: () => import('@/views/main/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('@/components/home.vue')
      },
      {
        path: '/user-info',
        component: () => import('@/components/person-center/userInfo.vue')
      },
      {
        path: '/user-avatar',
        component: () => import('@/components/person-center/changePic.vue')
      },
      {
        path: '/user-pwd',
        component: () => import('@/components/person-center/resetPassword.vue')
      },
      {
        path: '/art-cate',
        component: () => import('@/components/article-manage/articleCase.vue')
      },
      {
        path: '/art-list',
        component: () => import('@/components/article-manage/articleList.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
const whiteList = ['/login', '/reg']
// 全局前置路由守卫
// 1:浏览器第一次打开项目页面，会触发一次全局前置路由守卫函数
// 2: 判断登录与否: 有token就可以证明登录了，无token表明未登录
// 3:next() 如果强制切换路由地址，会再次走路由守卫再次去匹配路由表
router.beforeEach((to, from, next) => {
  // console.log(1)
  const token = store.state.token
  // 本地有token值,vuex中没有用户数据，才去请求用户信息(跳转路径会重复)
  if (token) {
    if (!store.state.userInfo.username) {
      store.dispatch('getUserInfo')
    }
    next()
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      // 未登录，可以访问的路由地址，则放行（路由全局前置守卫不会再次触发了）
      next()
    } else {
      // 未登录，强制打回登录页
      next('/login')
    }
  }
})
export default router
// 退出登入，重新登录，只走相关组件代码
// （异步dom切换，不会导致所有代码重新执行，APP.vue不走）
// 效果不对：换个账号它得需要重新请求用户数据
// 解决：
// 1.可以在登录页面，登录成功后再发请求去拿到用户信息
// 2.可以在全局前置路由守卫，写（路由跳转的时候，判断+获取）
